package cn.iocoder.ny.module.activity.service.impl;

import cn.iocoder.ny.module.activity.controller.admin.tpActivity.vo.TpActivityPageReqVo;
import cn.iocoder.ny.module.activity.controller.admin.tpActivity.vo.TpActivityRespVo;
import cn.iocoder.ny.module.activity.controller.admin.tpActivity.vo.TpActivityVo;
import cn.iocoder.ny.module.activity.domain.Activity;
import cn.iocoder.ny.module.activity.domain.TpActivity;
import cn.iocoder.ny.module.activity.mapper.TpActivityMapper;
import cn.iocoder.ny.module.activity.service.IActivityService;
import cn.iocoder.ny.module.activity.service.ITpActivityService;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.constant.WeChatAppConstants;
import cn.iocoder.yudao.module.system.dal.dataobject.system.SystemUsers;
import cn.iocoder.yudao.module.system.service.system.ISystemUserService;
import cn.iocoder.yudao.module.system.service.system.SystemUserServiceImpl;
import cn.iocoder.yudao.module.system.util.OkHttpUtils;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

/**
 * @author luchunhong
 * @date 2024/11/22/ 16:29
 * @description:
 */
@Service
public class ITpActivityServiceImpl extends ServiceImpl<TpActivityMapper, TpActivity> implements ITpActivityService {
    @Resource
    private IActivityService activityService;
    @Resource
    private TpActivityMapper tpActivityMapper;
    @Resource
    private ISystemUserService systemUserService;
    @Override
    public Boolean addTpActivity(TpActivityVo tpActivityVo) {
        LoginUser loginUser = getLoginUser();
        SystemUsers systemUserInfo = systemUserService.lambdaQuery().eq(SystemUsers::getId, loginUser.getId()).one();
        tpActivityVo.setMobile(systemUserInfo.getMobile());
        // 创建并存储活动
        Activity activity = createAndSaveActivity(tpActivityVo, loginUser.getTenantId());
        // 创建并存储投票活动
        TpActivity tpActivity = createTpActivity(tpActivityVo, activity.getId());
        return save(tpActivity);
    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @Override
    public PageResult<TpActivityRespVo> queryPageList(TpActivityPageReqVo reqVo) {
        LoginUser loginUser = getLoginUser();
        SystemUsers systemUserInfo = systemUserService.lambdaQuery().eq(SystemUsers::getId, loginUser.getId()).one();
        reqVo.setMobile(systemUserInfo.getMobile());
        IPage<TpActivityRespVo> page = new Page<>(reqVo.getPageNo(), reqVo.getPageSize());
        tpActivityMapper.queryPageList(page,reqVo);
        return new PageResult<>(page.getRecords(),page.getTotal());
    }

    /**
     * 根据活动id查询投票活动信息
     * @param tpActivityVo
     * @return
     */
    @Override
    public TpActivityRespVo queryByActivityId(TpActivityVo tpActivityVo) {
        TpActivityRespVo tpActivityRespVo = tpActivityMapper.queryByActivityId(tpActivityVo);
        return tpActivityRespVo;
    }

    @Override
    public String createActivityQrCode(TpActivityVo tpActivityVo) {
        return generateQrCode(tpActivityVo, "pages/shopping/index");
    }

    @Override
    public String createAdminActivityQrCode(TpActivityVo tpActivityVo) {
        return generateQrCode(tpActivityVo, "pages/manage/index");
    }

    @Override
    public Boolean updateTpActivity(TpActivity tpActivity) {
        boolean b = updateById(tpActivity);
        if (b){
            return true;
        }
        throw new RuntimeException("修改失败");
    }

    private String generateQrCode(TpActivityVo tpActivityVo, String page) {
        String wxToken = getWXToken("wxb0aa27c834339d33", "oKnDC5PMe5MJI7Owa0cxNCH5jcmQ");

        // 请求 URL
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + wxToken;

        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        // 构建 scene 参数
        String scene = "activity=" + tpActivityVo.getActivityId();
        if (scene.length() > 32) {
            scene = scene.substring(0, 32);
        }
        params.put("scene", scene);
        params.put("env_version", "trial");
        params.put("check_path", false);

        // 将参数转换为 JSON 格式
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonParams = gson.toJson(params);

        HttpURLConnection connection = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 写入请求参数
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                // 将字节数组转换为 Base64 编码字符串
                return Base64.getEncoder().encodeToString(imageBytes);
            } else {
                System.out.println(responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }



    /**
     * 创建且存储活动
     * @param tpActivityVo
     * @param tenantId
     * @return
     */
    private Activity createAndSaveActivity(TpActivityVo tpActivityVo, Long tenantId) {
        Activity activity = new Activity();
        activity.setTenantId(tenantId);
        activity.setStartTime(tpActivityVo.getStartTime());
        activity.setMobile(tpActivityVo.getMobile());
        activity.setExpireTime(tpActivityVo.getExpireTime());
        activity.setTypeId(1L);
        activity.setApplicationTime(tpActivityVo.getLocationTime());
        activity.setRegistrationDeadtime(tpActivityVo.getRegistrationDeadtime());
        activityService.save(activity);
        return activity;
    }

    /**
     * 创建且存储投票活动
     * @param tpActivityVo
     * @param activityId
     * @return
     */
    private TpActivity createTpActivity(TpActivityVo tpActivityVo, Long activityId) {
        TpActivity tpActivity = new TpActivity();
        tpActivity.setActivityId(activityId);
        tpActivity.setHeadImage(tpActivityVo.getHeadImage());
        tpActivity.setTpDetails(tpActivityVo.getTpDetails());
        tpActivity.setTpTotalNumber(tpActivityVo.getTpTotalNumber());
        tpActivity.setTpEveryDay(tpActivityVo.getTpEveryDay());
        tpActivity.setTpTemplateId(tpActivityVo.getTpTimplateId());
        tpActivity.setCode(tpActivityVo.getCode());
        tpActivity.setMobile(tpActivityVo.getMobile());
        tpActivity.setNickname(tpActivityVo.getNickname());
        tpActivity.setTpMusic(tpActivityVo.getTpMusic());
        tpActivity.setMarquee(tpActivityVo.getMarquee());
        return tpActivity;
    }

    @SneakyThrows
    private String getWXToken(String appid,String secret){
        String message = OkHttpUtils.builder().url(WeChatAppConstants.PHONETOKENURL)
                // 有参数的话添加参数，可多个
                .addParam("grant_type", "client_credential")
                .addParam("secret", secret)
                .addParam("appid", appid)
                //.addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                // 可选择是同步请求还是异步请求
                .async();
        Map<String, Object> map = JSON.parseObject(message, Map.class);
        String access_token = String.valueOf(map.get("access_token"));
        if (null==access_token){
            throw  new Exception("小程序登录失败，请联系管理员");

        }
        return access_token;

    }
}
